package com.uinnova.product.eam.web.eam.mvc;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.binary.core.util.BinaryUtils;
import com.binary.framework.web.RemoteResult;
import com.binary.jdbc.Page;
import com.uinnova.product.cj.feign.dto.PlanDesignInstanceDTO;
import com.uinnova.product.eam.base.exception.ServerException;
import com.uinnova.product.eam.comm.model.es.EamCategory;
import com.uinnova.product.eam.model.cj.domain.PlanDesignInstance;
import com.uinnova.product.eam.service.EamCategorySvc;
import com.uinnova.product.eam.service.EamDiagramRelationSysService;
import com.uinnova.product.eam.service.ICISwitchSvc;
import com.uinnova.product.eam.service.ShareDiagramSvc;
import com.uinnova.product.eam.service.cj.service.PlanDesignInstanceService;
import com.uinnova.product.vmdb.comm.doc.annotation.ModDesc;
import com.uinnova.product.vmdb.comm.doc.annotation.MvcDesc;
import com.uinnova.project.api.diagram.v2.client.ESDiagramApiClient;
import com.uinnova.project.base.diagram.comm.diagram.ESDiagramShareRecordResult;
import com.uinnova.project.base.diagram.comm.diagram.ShareRecordQueryBean;
import com.uinnova.project.base.diagram.comm.model.ESDiagram;
import com.uinnova.project.db.eam.ESDiagramDao;
import com.uinnova.project.service.eam.ESShareDiagramSvc;
import com.uino.bean.cmdb.base.ESCIInfo;
import com.uino.bean.cmdb.base.LibType;
import com.uino.bean.permission.base.SysUser;
import com.uino.util.sys.SysUtil;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/design/shareDiagram")
@MvcDesc(author="wang",desc="提供视图历史增删改查接口")
public class EamShareDesignDiagramMVC {
	@Resource
	private EamCategorySvc categorySvc;
	@Resource
	private ICISwitchSvc ciSwitchSvc;

	@Autowired
	private ESShareDiagramSvc esShareDiagramSvc;

	@Autowired
	private ShareDiagramSvc shareDiagramSvc;

	@Resource
	private EamDiagramRelationSysService eamDiagramRelationSysService;

	@Resource
	private ESDiagramDao esDiagramDao;

	@Resource
	private ESDiagramApiClient esDiagramApiClient;

	@Resource
	private PlanDesignInstanceService planDesignInstanceService;

	@PostMapping("/querySharedDiagramPage")
	@ModDesc(desc = "分页查询分享给我的视图", pDesc = "", rDesc = "", rType = List.class)
	public RemoteResult querySharedDiagramPage(@RequestBody ShareRecordQueryBean queryBean) {
		Page<ESDiagramShareRecordResult> resultPage = shareDiagramSvc.queryShareDirgram(queryBean);
		return new RemoteResult(resultPage);
	}

	@PostMapping("/querySharedDiagramFeign")
	@ModDesc(desc = "分页查询分享给我的视图", pDesc = "", rDesc = "", rType = List.class)
	public List<ESDiagramShareRecordResult> querySharedDiagramFeign(@RequestBody ShareRecordQueryBean queryBean) {
		Page<ESDiagramShareRecordResult> resultPage = shareDiagramSvc.queryShareDirgram(queryBean);
		return resultPage.getData();
	}

	@PostMapping("/feign/querySharedDiagramPage")
	@ModDesc(desc = "分页查询分享给我的视图", pDesc = "", rDesc = "", rType = List.class)
	public List<ESDiagramShareRecordResult> queryShare(@RequestBody ShareRecordQueryBean queryBean) {
		Page<ESDiagramShareRecordResult> resultPage = shareDiagramSvc.queryShareDirgram(queryBean);
		if (resultPage.getTotalRows() == 0) {
			return Collections.emptyList();
		}

		List<ESDiagram> diagrams =
				resultPage.getData().stream().map(ESDiagramShareRecordResult::getEsDiagram).collect(Collectors.toList());

		eamDiagramRelationSysService.esDiagramSetRelationProperties(diagrams);
		return resultPage.getData();
	}
/*
	@PostMapping("/queryDiagramShareRecords")
	@ModDesc(desc = "查询视图分享记录", pDesc = "", rDesc = "", rType = List.class)
	public RemoteResult queryDiagramShareRecords(HttpServletRequest request, HttpServletResponse response,
										 @RequestBody ShareRecordQueryBean shareRecordQueryBean) {
		String diagramId = shareRecordQueryBean.getDiagramId();
		Map<Long, List<ESDiagramShareRecordResult>> resultMap = esShareDesignDiagramSvc.queryDiagramShareRecords(new
		String[]{diagramId}, true);
		return new RemoteResult(resultMap);
	}*/

	@GetMapping("/addUserByLink")
	@ModDesc(desc = "链接授权用户视图权限", pDesc = "", rDesc = "", rType = List.class)
	public RemoteResult addUserByLink(@RequestParam String id) {
		JSONObject result = new JSONObject();
		String energyId = esShareDiagramSvc.addUserByLink(id);
//		EamDiagramCatalog eamDiagramCatalog = esDiagramCatalogSvc.selectByDiagramId(energyId, null, LibType.PRIVATE);
		EamCategory category = categorySvc.selectByDiagramId(energyId, null, LibType.PRIVATE);
		result.put("diagramId", energyId);
		long attachCiId = 0L;
		String attachCiCode = "";
		if(category != null && !BinaryUtils.isEmpty(category.getCiCode())){
			Page<ESCIInfo> ciPage = ciSwitchSvc.getESCIInfoPageByQuery(1L,1, 1, QueryBuilders.termQuery("ciCode.keyword", category.getCiCode()), Collections.emptyList(), false, LibType.PRIVATE);
			if(!BinaryUtils.isEmpty(ciPage.getData())){
				attachCiId = ciPage.getData().get(0).getId();
				attachCiCode = category.getCiCode();
			}
		}
		result.put("attachCiId", attachCiId);
		result.put("attachCiCode", attachCiCode);
		List<ESDiagram> esDiagrams = esDiagramDao.getListByQuery(QueryBuilders.termsQuery("dEnergy.keyword", energyId));
		if (!BinaryUtils.isEmpty(esDiagrams.get(0).getViewType())) {
			result.put("viewType", esDiagrams.get(0).getViewType());
		}
		if (!BinaryUtils.isEmpty(esDiagrams.get(0).getDirType())) {
			result.put("dirType", esDiagrams.get(0).getDirType());
		}
		return new RemoteResult(result);
	}

	/**
	 * 查询方案中视图的权限
	 */
	@PostMapping("/queryPlanDiagramPermission")
	public RemoteResult queryPlanDiagramPermission(@RequestBody JSONObject body) {
		JSONArray diagramIdJson = body.getJSONArray("diagramIds");
		SysUser userInfo = SysUtil.getCurrentUserInfo();
		if (diagramIdJson == null || diagramIdJson.size() <= 0) {
			throw new ServerException("视图参数不可为空!");
		}
		Long planId = body.getLong("planId");
		if (planId == null) {
			throw new ServerException("方案参数不可为空!");
		}
		PlanDesignInstanceDTO plan = null;
		PlanDesignInstance planDesignInstance = planDesignInstanceService.getPlanDesignInstance(planId);
		if (planDesignInstance != null) {
			plan = new PlanDesignInstanceDTO();
			BeanUtils.copyProperties(planDesignInstance, plan);
		}
		if (plan == null) {
			throw new ServerException("获取方案错误!");
		}
        Map<String, Integer> map = new HashMap<>();
		List<String> diagramIdList = diagramIdJson.toJavaList(String.class);
        List<ESDiagram> esDiagramList = esDiagramApiClient.queryDBDiagramInfoByIds(diagramIdList.toArray(new String[0]));
        if (CollectionUtils.isEmpty(esDiagramList)) {
            return new RemoteResult(map);
        } else {
            diagramIdList = esDiagramList.stream().map(ESDiagram::getDEnergy).collect(Collectors.toList());
        }
        Long[] diagramIds = esDiagramApiClient.queryDiagramInfoBydEnergy(diagramIdList.toArray(new String[]{}));
		// 查询视图分享的记录
		Map<Long, List<ESDiagramShareRecordResult>> resultMap = esShareDiagramSvc.queryDiagramShareRecords(diagramIds, false);
		for (Long diagramId : diagramIds) {
			ESDiagram esDiagram = esDiagramApiClient.querySimpleDiagramInfoById(diagramId);
			if (esDiagram == null) {
				throw new ServerException("存在已被删除的视图!");
			}
			if (Objects.equals(userInfo.getLoginCode(), plan.getCreatorCode()) && Objects.equals(plan.getCreatorCode(), esDiagram.getOwnerCode())) {
				map.put(esDiagram.getDEnergy(), 1);
			} else if (Objects.equals(userInfo.getLoginCode(), esDiagram.getOwnerCode())){
				map.put(esDiagram.getDEnergy(), 1);
			} else {
				List<ESDiagramShareRecordResult> esDiagramShareRecordResults = resultMap.get(diagramId);
				if (!CollectionUtils.isEmpty(esDiagramShareRecordResults)) {
					List<String> sharedLoginCode = new ArrayList<>(esDiagramShareRecordResults.size());
					esDiagramShareRecordResults.forEach(esDiagramShare -> {
						if (Objects.equals(esDiagramShare.getPermission(), 1) || Objects.equals(esDiagramShare.getPermission(), 2)) {
							SysUser sharedSysUser = esDiagramShare.getSharedSysUser();
							if (sharedSysUser != null && !StringUtils.isEmpty(sharedSysUser.getLoginCode())) {
								sharedLoginCode.add(sharedSysUser.getLoginCode());
							}
						}
					});
					if (sharedLoginCode.contains(userInfo.getLoginCode())) {
						map.put(esDiagram.getDEnergy(), 1);
					} else {
						map.put(esDiagram.getDEnergy(), 0);
					}
				} else {
					map.put(esDiagram.getDEnergy(), 0);
				}
			}
		}
		return new RemoteResult(map);
	}

}
